package com.wjm.serversocket.test1;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class UploadTask implements Runnable {
    private String fileName;
    private Socket socket;

    public UploadTask(String fileName, Socket socket) {
        this.fileName = fileName;
        this.socket = socket;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"run==》"+fileName+"开始上传");
        try {
            int count = 0;
            String ip = socket.getInetAddress().getHostAddress();
            System.out.println(ip + ".......connected");
            InputStream socketIs = socket.getInputStream();


            File fileDir = new File(UploadPicServer.pcPf + File.separator + UploadPicServer.serverfilePath);//i:\\server
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
            UUID uuid = UUID.randomUUID();
            String simpleDateFormatStr = new SimpleDateFormat("yyyyMMddHHmmssSSS_").format(new Date()).toString()+uuid;
            File file = new File(fileDir, simpleDateFormatStr + fileName);

            if (file.exists()) {
                count++;
                file = new File(fileDir, simpleDateFormatStr + UploadPicServer.fileNameStart + "(" + count + ")" + UploadPicServer.fileMp4);
            }
            if (file.exists()) {
                count++;
                file = new File(fileDir, simpleDateFormatStr + UploadPicServer.fileNameStart + "(" + count + ")" + UploadPicServer.fileMp4);
            }


            System.out.println(Thread.currentThread().getName()+"run==》"+file+"文件创建了");

            FileOutputStream fos = new FileOutputStream(file);

            byte[] buf = new byte[10240];
//            byte[] buf = new byte[1024];
            int len;
            while ((len = socketIs.read(buf)) != -1) {
                fos.write(buf, 0, len);
                Thread.sleep(1);
            }
            socket.shutdownOutput();//不发结束字符，发结束标记
            System.out.println(Thread.currentThread().getName()+"文件==》"+file+"上传完成");

//            OutputStream out = socket.getOutputStream();
//            out.write("上传成功".getBytes());

            fos.close();

            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }
}